import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import routes from './routes'
import 'font-awesome/css/font-awesome.min.css'
import axios from 'axios'
import jwt from 'jsonwebtoken';
import Login from "./views/Login.vue";
import NotFound from "./views/404.vue";
import Home from "./views/Home.vue";
import Echarts from "./views/charts/Echarts.vue";
import User from "./views/user/User.vue";
import Permission from "./views/system/Permission.vue";
import Menu from "./views/system/Menu.vue";
import Role from "./views/system/Role.vue";
import Article from "./views/blog/Article.vue";
import ArticleType from "./views/blog/ArticleType.vue";


//配置axios的全局基本路径
axios.defaults.baseURL = 'http://localhost:8080';
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)


const router = new VueRouter({
  routes
})


//初始化菜单
initMenu();

//初始化菜单
function initMenu(){
  //获取token
  let token = localStorage.getItem("token");
  //token有值，才来解析
  if(token){
    try{
      let resultObj = jwt.decode(token);
      let {menus} = resultObj.payload;
      console.log(menus)
      //如果菜单有值，我们就循环动态拼接
      if(menus&&menus.length){
        for(let i=0;i<menus.length;i++){
          //获取一级菜单
          let menu = menus[i];
          //一级菜单
          let indexRouter = {
            path: '/',
            component: resolve => require(['@/views/Home'], resolve),
            name: menu.name,
            iconCls: menu.icon,//图标样式class
            children: []
          }
          //添加一级菜单
          routes.push(indexRouter);
          //拿到儿子菜单
          let children = menu.children;
          for(let j=0;j<children.length;j++){
            //拿到具体的儿子
            let childMenu = children[j];
            indexRouter.children.push({
              path: childMenu.url,
              component: resolve => require(['@/views/'+childMenu.component], resolve),
              name: childMenu.name
            })
          }
        }
        //让动态路由生效
        router.addRoutes(routes);
      }
    }catch(e){
      alert("非法参数!!!");
      return;
    }
  }else{
    return;
  }
}


//axios前置拦截器(只要发送axios之前，它会先执行匿名函数中的代码)
axios.interceptors.request.use(config => {
  if (localStorage.getItem('token')) {
    // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['token'] = localStorage.getItem('token');
  }
  return config
}, error => {
  console.log('request拦截器 - 发生异常：');
  Promise.reject(error);
});

//axios的响应拦截器
axios.interceptors.response.use(res => {
  let {success,code,message} = res.data;
  if(!success&&code==401){
    //跳转到登录界面
    ElementUI.Message({
      message: message,
      type: 'error'
    });
    router.push({ path: '/login' });
    return ;
  }else if(!success&&code==403){
    ElementUI.Message({
      message: message,
      type: 'error'
    });
    return;
  }
  return res;
}, err => {
  // 在请求错误时要做的事儿
  // 该返回的数据则是axios.catch(err)中接收的数据
  return Promise.reject(err)
});

//每次路由之前都要执行,每次请求都要经过路由
//每次请求都不拦截到
router.beforeEach((to, from, next) => {
  console.log(to.path);
  //NProgress.start();
  if (to.path == '/login') {
    //重新登录,把原来session移除掉
    localStorage.removeItem('token');
  }else{
    //获取token
    let token = localStorage.getItem("token");
    if(!token){
      router.push({ path: '/login' });
      return;
    }
    try{
      jwt.decode(token);
    }catch(e){
      router.push({ path: '/login' });
      return;
    }
  }
  next();
})

new Vue({
  router,
  store,
  render: h => h(App) // index.html id为app的div标签下面使用<App/>和template: '<App/>',一样的效果
}).$mount('#app') // 和el: '#app'效果一样都是挂载在index.html id为app的div标签上面

